<template>
  <div class="train-wrapper">
    <div class="form-container">
      <div class="rule_title">
        <span class="title-l"> <i class="icon_left"></i>{{ titleTip }} </span>
        <el-link
          @click="handleClickClose"
          class="icon-right"
          icon="el-icon-refresh-left"
          type="primary"
        >
          返回上一页
        </el-link>
      </div>
      <el-form
        label-position="right"
        :model="ruleForm"
        class="quality-file inputForm"
        label-width="140px"
        :inline="true"
        :rules="rules"
        ref="ruleForm"
        :disabled="disable || effected"
      >
        <div class="range_tab">
          基本信息
          <div
            style="float: right; padding-right: 10px; font-weight: 400"
            v-if="isJoinOrigin"
          >
            <div v-if="nowUser.status === 0">
              <el-tag type="info">未参加</el-tag>
            </div>
            <div v-else>
              参加时间: <span v-time="nowUser.attend_time"></span>
            </div>
          </div>
        </div>
        <el-row :gutter="24">
          <el-form-item label="培训名称" prop="plan_training_name">
            <el-input v-model="ruleForm.plan_training_name"></el-input>
          </el-form-item>
          <el-form-item label="培训时间" prop="plan_training_time">
            <el-date-picker
              v-model="ruleForm.plan_training_time"
              type="datetime"
              placeholder="选择日期时间"
              value-format="timestamp"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="培训讲师" prop="plan_training_lecturer">
            <el-select
              v-model="ruleForm.plan_training_lecturer"
              filterable
              clearable
            >
              <el-option
                v-for="handler in staffData"
                :key="handler.id"
                :label="handler.name"
                :value="handler.id * 1"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="培训地点" prop="training_place">
            <el-input v-model="ruleForm.training_place"></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="24">
          <el-form-item label="培训范围" prop="plan_training_role">
            <el-select
              @change="handleChangeRole"
              v-model="ruleForm.plan_training_role"
              filterable
              clearable
            >
              <el-option
                v-for="(item, index) in categoryData"
                :key="index"
                :label="item.value"
                :value="item.key * 1"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="plan_training_role_ids">
            <el-cascader
              size="mini"
              @change="handleChangeUser"
              v-if="ruleForm.plan_training_role === 1"
              ref="cascader"
              :options="branchData"
              :show-all-levels="false"
              v-model="ruleForm.plan_training_role_ids"
              :props="{
                emitPath: false,
                checkStrictly: true,
                label: 'branch_name',
                value: 'id',
                children: 'next_level_data',
                multiple: true,
              }"
              filterable
              clearable
            >
            </el-cascader>
            <el-select
              @change="handleChangeUser"
              v-if="ruleForm.plan_training_role === 2"
              multiple
              v-model="ruleForm.plan_training_role_ids"
              filterable
              clearable
            >
              <el-option
                v-for="item in roleList"
                :label="item.name"
                :value="item.id"
                :key="item.id * 1"
                >{{ item.name }}</el-option
              >
            </el-select>
            <el-select
              @change="handleChangeUser"
              v-if="ruleForm.plan_training_role === 3"
              multiple
              v-model="ruleForm.plan_training_role_ids"
              filterable
              clearable
            >
              <el-option
                v-for="handler in staffData"
                :key="handler.id"
                :label="handler.name"
                :value="handler.id * 1"
              />
            </el-select>
            <el-select
              @change="handleChangeUser"
              v-if="ruleForm.plan_training_role === 4"
              multiple
              v-model="ruleForm.plan_training_role_ids"
              filterable
              clearable
            >
              <el-option
                v-for="item in companyData"
                :label="item.name"
                :value="item.id * 1"
                :key="item.id"
                >{{ item.name }}</el-option
              >
            </el-select>
          </el-form-item>
          <el-form-item
            label="文件说明模板"
            prop="file_comment_template_id"
            style="margin-left: -10px"
            class="select-add"
          >
            <el-select
              style="width: 148px"
              v-model="ruleForm.file_comment_template_id"
              class="select-left"
              filterable
              placeholder="请选择"
            >
              <el-option
                v-for="item in templateData"
                :label="item.template_name"
                :value="item.id"
                :key="item.id"
              ></el-option>
            </el-select>
            <el-button @click="handleAddTemplate" class="add-right">
              +
            </el-button>
            <span
              @click="goList"
              style="margin-left: 7px; color: #66b1ff; cursor: pointer"
              >去管理</span
            >
          </el-form-item>
        </el-row>
        <div class="range_tab">培训项</div>
        <div style="padding-bottom: 10px">
          <el-button type="primary" plain size="mini" @click="handleAddMaterial"
            >新增</el-button
          >

          <el-button type="primary" plain size="mini" @click="handleDelMaterial"
            >删除</el-button
          >
        </div>
        <el-table
          :data="ruleForm.plan_training_items"
          @selection-change="handleSelectionChange"
          border
          stripe
          style="margin-bottom: 16px"
          :row-class-name="tableRowClassName"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column
            prop=""
            label="序号"
            width="50"
            type="index"
          ></el-table-column>
          <!-- <el-table-column prop="date" label="名称" width="220">
            <template slot-scope="scope">
              <el-input v-model="scope.row['item_name']"></el-input>
            </template>
          </el-table-column> -->
          <el-table-column prop="date" label="内容" width="220">
            <template slot-scope="scope">
              <el-input v-model="scope.row['item_content']"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="date" label="材料" width="240">
            <template slot-scope="scope">
              <el-select
                multiple
                v-model="scope.row['item_material_ids']"
                filterable
                clearable
              >
                <el-option
                  v-for="handler in materialData"
                  :key="handler.id"
                  :label="handler.name"
                  :value="handler.id * 1"
                />
              </el-select>
              <el-button
                type="info"
                @click="handleClickMaterialAdd"
                style="padding: 5px; margin-left: 3px"
                size="mini"
                plain
                icon="el-icon-plus"
                circle
              ></el-button>
            </template>
          </el-table-column>
          <el-table-column
            prop="item_material_list"
            label="材料明细"
            v-if="isJoinOrigin"
          >
            <template slot-scope="scope">
              <div
                v-for="(item, index) in scope.row.item_material_list"
                :key="index"
              >
                <el-link :href="item.url" type="primary">{{
                  item.material_name
                }}</el-link>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="" label="" v-else> </el-table-column>
        </el-table>
        <template v-if="!isJoinOrigin">
          <el-form :disabled="disable">
            <div class="range_tab">参加人</div>
            <div style="padding-bottom: 10px">
              <el-popover
                v-if="
                  ruleForm.plan_training_role === 1 ||
                  ruleForm.plan_training_role === 2
                "
                placement="top"
                width="260"
                v-model="addDialogVisible"
              >
                <p style="padding-bottom: 10px">请选择要添加的账号(可多选)</p>
                <el-select multiple v-model="role_ids" filterable clearable>
                  <el-option
                    v-for="handler in staffData"
                    :key="handler.id"
                    :label="handler.name"
                    :value="handler.id * 1"
                  />
                </el-select>
                <div style="text-align: right; margin: 0; padding-top: 10px">
                  <el-button
                    size="mini"
                    type="text"
                    @click="handleAccountCancel"
                    >取消</el-button
                  >
                  <el-button type="primary" size="mini" @click="handleAccountOk"
                    >确定</el-button
                  >
                </div>
                <el-button
                  :disabled="effected"
                  slot="reference"
                  style="margin-right: 10px"
                  type="primary"
                  plain
                  size="mini"
                  @click="handleAddItem"
                  >新增</el-button
                >
              </el-popover>
              <!-- <el-button type="primary" plain size="mini" @click="handleUserAdd">新增</el-button> -->
              <el-button
                :disabled="effected"
                type="primary"
                plain
                size="mini"
                @click="handleUserDel"
                >删除</el-button
              >
              <el-button
                type="primary"
                v-show="effected"
                plain
                size="mini"
                @click="handleChangeStatus"
                >已参加</el-button
              >
            </div>
            <el-table
              :max-height="300"
              ref="userTable"
              :data="ruleForm.training_user"
              :key="Math.random()"
              @selection-change="handleUserSelectionChange"
              border
              stripe
              style="margin-bottom: 12px"
            >
              <el-table-column :disabled="false" type="selection" width="55">
              </el-table-column>
              <el-table-column
                fixed
                label="序号"
                width="50"
                type="index"
              ></el-table-column>
              <el-table-column prop="user_nickname" label="姓名" width="200">
              </el-table-column>
              <el-table-column prop="date" label="状态" width="200">
                <template slot-scope="scope">
                  <div>
                    {{ ["未参加", "已参加"][scope.row.status || "0"] }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="attend_time" label="参加时间" width="200">
                <template slot-scope="scope">
                  <div>
                    <span v-time="scope.row.attend_time"></span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="" label=""> </el-table-column>
            </el-table>
          </el-form>
        </template>
      </el-form>
    </div>
    <div class="operation-footer">
      <div class="footer-wrap">
        <el-button size="small" @click="handleClickClose">关闭</el-button>
        <el-button
          size="small"
          v-show="ruleForm.status === 1 || mode === 'add'"
          type="primary"
          @click="handleClickSubmit"
          >保存草稿</el-button
        >
        <template v-if="!isJoinOrigin && mode !== 'add'">
          <el-button
            size="small"
            v-show="ruleForm.status === 1"
            type="primary"
            @click="handleOperation('1')"
            >生效</el-button
          >
          <el-button
            size="small"
            v-show="ruleForm.status === 2"
            type="primary"
            @click="handleOperation('2')"
            >已培训</el-button
          >
          <el-button
            size="small"
            v-show="ruleForm.status !== 4"
            type="primary"
            @click="handleOperation('3')"
            >作废</el-button
          >
        </template>
        <el-button
          v-show="isJoinOrigin && nowUser.status === 0"
          size="small"
          type="primary"
          @click="handleOperation('5')"
          >已参加</el-button
        >
        <el-button
          size="small"
          v-if="mode !== 'add'"
          type="primary"
          @click="handleOperation('4')"
          >导出</el-button
        >
      </div>
    </div>
    <TrainMaterial
      mode="add"
      v-if="materialDialogVisible"
      :dialogVisible="materialDialogVisible"
      @close="handleCloseMaterialDialog"
    ></TrainMaterial>
    <FileTemplate
      mode="add"
      v-if="templateDialogVisible"
      :dialogVisible="templateDialogVisible"
      @close="handleCloseTemplateDialog"
    ></FileTemplate>
  </div>
</template>

<script>
import {
  trainingMaterialOptions,
  trainingPlanCreate,
  trainingPlanDetail,
  trainingPlanUpdate,
  trainingUserOption,
  trainingPlanTookeffect,
  trainingPlanTrained,
  trainingPlanCancellation,
  trainingPlanExport,
  trainingPlanStatusUpdate,
  FileTemplateOptions,
} from "@/api/qms";
import { AdminBox } from "@/api/customer";
import { organizationBox, roleBox } from "@/api/organization";
import { carrierBox } from "@/api/waybill";
import { downloadFile, timestamp10 } from "@/utils/mUtils";
import FinishTime from "./components/finishTime.vue";
import TrainMaterial from "./components/trainMaterial.vue";
import FileTemplate from "./components/fileTemplate.vue";
export default {
  name: "train",
  components: { TrainMaterial, FileTemplate },
  props: [],
  data() {
    return {
      ruleForm: {
        plan_training_items: [{}],
        training_user: [],
        training_type: 1,
        training_count: 1,
        status: 1,
      },
      mode: "",
      role_ids: [],
      addDialogVisible: false,
      titleTip: "培训计划",
      categoryData: [
        {
          key: "1",
          value: "组织",
        },
        {
          key: "2",
          value: "角色",
        },
        {
          key: "4",
          value: "承运商",
        },
        {
          key: "3",
          value: "账号",
        },
      ],
      staffData: [],
      branchData: [],
      roleList: [],
      companyData: [],
      accountData: [],
      materialData: [],
      checkedUser: [], //选中的参加人
      materialDialogVisible: false, //增加培训材料弹框
      rules: {},
      origin: "",
      nowUser: {},
      templateData: [],
      templateDialogVisible: false,
    };
  },
  computed: {
    disable() {
      return this.mode === "detail";
    },
    effected() {
      return this.ruleForm.status === 2 || this.ruleForm.status === 3;
    },
    isJoinOrigin() {
      return this.origin === "join";
    },
  },
  mounted() {
    this.mode = this.$route.query.mode || "add";
    this.origin = this.$route.query.origin;
    // // console.log(this.$route.query,"this.$route.query")
    if (this.$route.query.type) {
      this.ruleForm.plan_training_role = this.$route.query.type * 1;
      this.ruleForm.plan_training_role_ids = this.$route.query.id;
    }
    AdminBox({
      user_type: "0",
    }).then((res) => {
      this.staffData = res.data;
    });
    organizationBox({ not_show_first_branch: 1 }).then((res) => {
      this.branchData = res.data;
    });
    roleBox().then((res) => {
      const data = res.data || [];
      this.roleList = data;
    });
    carrierBox().then((res) => {
      this.companyData = res.data;
    });

    // AdminBox({
    // }).then(res => {
    //   this.accountData = res.data;
    // });
    this.getTemplateData();
    this.getMaterialData();
    this.mode = this.$route.query.mode || "add";
    if (this.mode === "add") {
    } else if (this.mode === "detail" || this.mode === "edit") {
      this.getDetail();
    }
  },
  methods: {
    goList() {
      let text = this.$router.resolve({ name: "fileTemplateList" });
      window.open(text.href, "_blank");
    },
    // 添加文件模板
    handleAddTemplate() {
      this.templateDialogVisible = true;
    },
    tableRowClassName({ row, rowIndex }) {
      row.index = rowIndex;
    },
    handleLook(scope) {
      // console.log(scope, 'eeee');
    },
    getMaterialData() {
      trainingMaterialOptions({}).then((res) => {
        this.materialData = res.data;
      });
    },
    getTemplateData() {
      FileTemplateOptions({}).then((res) => {
        this.templateData = res.data.data;
      });
    },
    handleAccountOk() {
      // 去重后的id
      const _role_ids = this.role_ids.filter(
        (x) =>
          this.ruleForm.training_user.findIndex((y) => y.user_id === x) === -1
      );
      this.staffData.forEach((item) => {
        if (_role_ids.includes(item.id)) {
          this.ruleForm.training_user.push({
            user_id: item.id,
            user_nickname: item.nickname,
          });
        }
      });
      this.addDialogVisible = false;
    },
    handleClickMaterialAdd() {
      this.materialDialogVisible = true;
    },
    handleCloseMaterialDialog(isUpdate) {
      this.materialDialogVisible = false;
      isUpdate && this.getMaterialData();
    },
    handleCloseTemplateDialog(isUpdate) {
      this.templateDialogVisible = false;
      isUpdate && this.getTemplateData();
    },
    handleAccountCancel() {
      this.role_ids = [];
      this.addDialogVisible = false;
    },
    handleChangeStatus() {
      const title = "已参加";
      this.$msgbox({
        message: (
          <FinishTime
            title={title}
            key={Date.now()}
            hanldeOk={this.handleFinish}
          ></FinishTime>
        ),
        customClass: "temperature_msg",
        showConfirmButton: false,
        showCancelButton: false,
        showClose: true,
        title,
      });
    },
    handleFinish(time) {
      // this.ruleForm.training_user.forEach(item => {
      //   if (this.checkedUser.includes(item.user_id)) {
      //     item.status = 1;
      //     item.attend_time = time*1;
      //   }
      // });
      trainingPlanStatusUpdate({
        id: this.ruleForm.id,
        user_ids: this.checkedUser,
        status: "1",
        attend_time: time * 1,
        training_count: 0,
      }).then((res) => {
        if (res.code === 10000) {
          this.getDetail();
          this.$refs.userTable.clearSelection();
        }
      });
    },
    handleUserAdd() {},
    handleUserDel() {
      // console.log(this.checkedUser, this.ruleForm.training_user.filter(item => !this.checkedUser.includes(item.user_id)), 'this.ruleForm.training_user.filter(item=> !this.checkedUser.includes(item.user_id))');
      this.ruleForm.training_user = this.ruleForm.training_user.filter(
        (item) => !this.checkedUser.includes(item.user_id)
      );
    },
    handleUserSelectionChange(checked) {
      this.checkedUser = checked.map((item) => item.user_id);
    },
    handleSelectionChange(checked) {
      this.checkedMaterial = checked.map((item) => item.index);
    },
    handleAddMaterial() {
      this.ruleForm.plan_training_items.push({});
    },
    handleDelMaterial() {
      this.ruleForm.plan_training_items =
        this.ruleForm.plan_training_items.filter(
          (item) => !this.checkedMaterial.includes(item.index)
        );
    },
    handleClose() {
      this.$router.push({
        name: "trainManageList",
      });
    },

    handleChangeRole() {
      this.ruleForm.plan_training_role_ids = [];
      this.ruleForm.training_user = [];
    },
    handleChangeUser() {
      if (
        this.ruleForm.plan_training_role === 1 ||
        this.ruleForm.plan_training_role === 2
      ) {
        trainingUserOption({
          range_type: this.ruleForm.plan_training_role, // 1-组织，2-角色
          range_ids: this.ruleForm.plan_training_role_ids,
        }).then((res) => {
          let data = res.data.list;
          data = data.map((item) => {
            return {
              user_id: item.id,
              user_nickname: item.nickname,
            };
          });
          this.ruleForm.training_user = data;
        });
      } else if (this.ruleForm.plan_training_role === 3) {
        const staffs = this.staffData.filter((item) =>
          this.ruleForm.plan_training_role_ids.includes(item.id)
        );
        this.ruleForm.training_user = staffs.map((item) => {
          return {
            user_id: item.id,
            user_nickname: item.nickname,
          };
        });
      } else if (this.ruleForm.plan_training_role === 4) {
        const companys = this.companyData.filter((item) =>
          this.ruleForm.plan_training_role_ids.includes(item.id)
        );
        this.ruleForm.training_user = companys.map((item) => {
          return {
            user_id: item.id,
            user_nickname: item.name,
          };
        });
      }
    },
    // trainingPlanTookeffect,trainingPlanTrained,
    // trainingPlanCancellation,trainingPlanExport
    handleOperation(type) {
      switch (type) {
        case "1":
          if ((this.ruleForm.training_user || []).length === 0) {
            this.$message({
              message: "请添加参加人",
              type: "warning",
            });
            return;
          }
          trainingPlanTookeffect({
            id: this.ruleForm.id * 1,
          }).then((res) => {
            if (res.code === 10000) {
              this.$message({
                message: "培训计划已生效",
                type: "success",
              });
              this.getDetail();
            }
          });
          break;
        case "2":
          trainingPlanTrained({
            id: this.ruleForm.id * 1,
          }).then((res) => {
            if (res.code === 10000) {
              this.$message({
                message: "已培训",
                type: "success",
              });
              this.getDetail();
            }
          });
          break;
        case "3":
          trainingPlanCancellation({
            id: this.ruleForm.id * 1,
          }).then((res) => {
            if (res.code === 10000) {
              this.$message({
                message: "培训计划已作废",
                type: "success",
              });
            }
          });
          break;
        case "4":
          trainingPlanExport({
            id: this.ruleForm.id * 1,
          }).then((res) => {
            if (res.code === 10000) {
              downloadFile(
                `培训_${this.ruleForm.plan_training_name}`,
                res.data.data
              );
            }
          });
          break;
        case "5":
          this.checkedUser = [this.$store.state.user.user_id];
          this.handleChangeStatus();
        default:
          break;
      }
    },
    // 获取文件详情
    getDetail() {
      trainingPlanDetail({
        id: this.$route.query.id * 1,
      }).then((res) => {
        const data = res.data.data;
        data.plan_training_time = data.plan_training_time * 1000;
        data.plan_training_name = data.name;
        data.plan_training_role = data.plan_role;
        data.plan_training_role_ids = data.plan_training_role_list.map(
          (item) => item.plan_training_role_id
        );
        data.plan_training_lecturer = data.plan_training_lecturer;
        data.training_user = data.plan_training_user;
        data.plan_training_items = data.plan_training_items || [];
        data.plan_training_items.forEach((item) => {
          item.item_material_ids = (item.item_material_list || []).map(
            (item) => item.id
          );
        });
        this.ruleForm = data;
        if (this.isJoinOrigin) {
          this.nowUser =
            this.ruleForm.training_user.find(
              (item) => item.user_id == this.$store.state.user.user_id
            ) || {};
        }

        // console.log(nowUser, this.$store.state.user.user_id, 'nowUser');
      });
    },
    handleClickSubmit() {
      this.$refs["ruleForm"].validate((valid) => {
        if (!valid) return;
        const _ruleForm = {
          ...this.ruleForm,
          plan_training_time: timestamp10(this.ruleForm.plan_training_time) * 1,
          plan_training_user: this.ruleForm.training_user,
        };
        if (this.mode === "add") {
          trainingPlanCreate(_ruleForm).then((res) => {
            if (res.code === 10000) {
              this.$message({
                message: "保存成功",
                type: "success",
              });
              this.$router.go(-1);
            }
          });
        } else {
          trainingPlanUpdate(_ruleForm).then((res) => {
            if (res.code === 10000) {
              this.$message({
                message: "修改成功",
                type: "success",
              });
            }
          });
        }
      });
    },
    handleClickClose() {
      this.$router.go(-1);
    },
    handleAddItem() {},
  },
};
</script>
<style lang="scss" scoped>
.train-wrapper {
  background: #fff;

  min-height: 100vh;
  box-sizing: border-box;

  .form-container {
    padding: 20px;
  }

  .rule_title {
    // background: red;
    display: flex;
    align-items: center;
    padding-bottom: 18px;
    padding-top: 8px;
    font-size: 14px;
    font-weight: bold;
    justify-content: space-between;

    .title-l {
      display: flex;
      align-items: center;
    }

    .icon_left {
      display: inline-block;
      width: 6px;
      height: 16px;
      background: #f1a357;
      margin-right: 6px;
    }

    .icon-right {
    }
  }

  .range_tab {
    width: 100%;
    height: 30px;
    background: #f2f3f5;
    font-weight: bold;
    line-height: 30px;
    padding-left: 12px;
    margin-bottom: 16px;
    color: #6d6e72;
    font-size: 14px;
  }

  .operation-footer {
    position: fixed;
    width: 100%;
    bottom: 0;
    background: white;
    box-sizing: border-box;
    padding: 15px 0;
    box-shadow: 0px -10px 20px -10px rgba(0, 0, 0, 0.07);
    z-index: 100;

    .footer-wrap {
      width: 86.3%;
      text-align: center;
    }
  }
}
.inputForm {
  .el-input {
    width: 180px;
  }

  .el-radio-group,
  .el-select,
  .el-cascader {
    width: 180px;
  }

  .el-textarea {
    width: 400px;
  }

  /deep/ .el-form-item {
    // margin-right: 30px !important;
  }
}
/deep/.inputForm
  .select-add
  .el-form-item__content
  > .select-left
  .el-input__inner {
  border-radius: 4px 0 0 4px;
}
/deep/.inputForm .select-add .el-form-item__content {
  display: inline-flex;
  // float: left;
}
/deep/.inputForm .select-add .add-right {
  width: 30px;
  position: relative;
  // left: -28px;
  // top:2px;
  padding: 0;
  height: 28px;
  border-radius: 0 4px 4px 0;
  border-left-width: 0px;
  font-size: 18px;
  font-weight: bold;
}
/deep/.inputForm .select-add .add-right:active {
  border-color: #c6e2ff;
}
</style>